<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '240px'" class="sidebar">
      <div class="sidebar-header">
        <div v-if="!isCollapse" class="logo">
          <el-icon class="logo-icon"><Management /></el-icon>
          <span class="logo-text">管理后台</span>
        </div>
        <el-icon v-else class="logo-icon-collapsed"><Management /></el-icon>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :unique-opened="true"
        router
        class="sidebar-menu"
      >
        <el-menu-item index="/admin/dashboard">
          <el-icon><Odometer /></el-icon>
          <template #title>仪表盘</template>
        </el-menu-item>
        
        <el-sub-menu index="user-management">
          <template #title>
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </template>
          <el-menu-item index="/admin/users/students">学生管理</el-menu-item>
          <el-menu-item index="/admin/users/organizers">组织者管理</el-menu-item>
          <el-menu-item index="/admin/users/admins">管理员管理</el-menu-item>
        </el-sub-menu>
        
        <el-menu-item index="/admin/activities">
          <el-icon><Calendar /></el-icon>
          <template #title>活动管理</template>
        </el-menu-item>
        
        <el-menu-item index="/admin/registrations">
          <el-icon><Tickets /></el-icon>
          <template #title>报名管理</template>
        </el-menu-item>
        
        <el-menu-item index="/admin/feedback">
          <el-icon><ChatDotRound /></el-icon>
          <template #title>反馈管理</template>
        </el-menu-item>
        
        <el-sub-menu index="system-management">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>系统管理</span>
          </template>
          <el-menu-item index="/admin/system/settings">系统设置</el-menu-item>
          <el-menu-item index="/admin/system/logs">操作日志</el-menu-item>
          <el-menu-item index="/admin/system/backup">数据备份</el-menu-item>
        </el-sub-menu>
        
        <el-menu-item index="/admin/statistics">
          <el-icon><DataAnalysis /></el-icon>
          <template #title>数据统计</template>
        </el-menu-item>
      </el-menu>
    </el-aside>
    
    <!-- 主要内容区域 -->
    <el-container class="main-container">
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="header-left">
          <el-button 
            type="text" 
            @click="toggleSidebar"
            class="collapse-btn"
          >
            <el-icon><Expand v-if="isCollapse" /><Fold v-else /></el-icon>
          </el-button>
          
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item 
              v-for="item in breadcrumbList" 
              :key="item.path"
              :to="item.path"
            >
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="header-right">
          <!-- 通知 -->
          <el-dropdown @command="handleNotificationCommand">
            <el-button type="text" class="notification-btn">
              <el-badge :value="unreadNotifications" :hidden="unreadNotifications === 0">
                <el-icon><Bell /></el-icon>
              </el-badge>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <div class="notification-header">
                  <span>通知消息</span>
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="markAllAsRead"
                    :disabled="unreadNotifications === 0"
                  >
                    全部已读
                  </el-button>
                </div>
                
                <div v-if="notifications.length === 0" class="notification-empty">
                  <el-empty description="暂无通知" :image-size="60" />
                </div>
                
                <div v-else class="notification-list">
                  <div 
                    v-for="notification in notifications.slice(0, 5)" 
                    :key="notification.id"
                    class="notification-item"
                    :class="{ 'unread': !notification.read }"
                    @click="markAsRead(notification.id)"
                  >
                    <div class="notification-content">
                      <div class="notification-title">{{ notification.title }}</div>
                      <div class="notification-desc">{{ notification.content }}</div>
                      <div class="notification-time">{{ formatDate(notification.createdAt, 'MM-DD HH:mm') }}</div>
                    </div>
                    <div v-if="!notification.read" class="notification-dot"></div>
                  </div>
                </div>
                
                <el-dropdown-item command="viewAll" class="view-all">
                  查看全部通知
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <!-- 用户菜单 -->
          <el-dropdown @command="handleUserCommand">
            <div class="user-info">
              <el-avatar :size="32" :src="userInfo.avatar">
                <el-icon><UserFilled /></el-icon>
              </el-avatar>
              <span class="username">{{ userInfo.username }}</span>
              <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人信息
                </el-dropdown-item>
                <el-dropdown-item command="settings">
                  <el-icon><Setting /></el-icon>
                  系统设置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <!-- 主要内容 -->
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { formatDate } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  Management,
  Odometer,
  User,
  Calendar,
  Tickets,
  ChatDotRound,
  Setting,
  DataAnalysis,
  Expand,
  Fold,
  Bell,
  UserFilled,
  ArrowDown,
  SwitchButton
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const isCollapse = ref(false)
const unreadNotifications = ref(0)
const notifications = ref([])

const userInfo = reactive({
  username: '',
  avatar: '',
  role: 'admin'
})

// 面包屑导航映射
const breadcrumbMap = {
  '/admin/dashboard': [{ title: '仪表盘', path: '/admin/dashboard' }],
  '/admin/users/students': [
    { title: '用户管理', path: '' },
    { title: '学生管理', path: '/admin/users/students' }
  ],
  '/admin/users/organizers': [
    { title: '用户管理', path: '' },
    { title: '组织者管理', path: '/admin/users/organizers' }
  ],
  '/admin/users/admins': [
    { title: '用户管理', path: '' },
    { title: '管理员管理', path: '/admin/users/admins' }
  ],
  '/admin/activities': [{ title: '活动管理', path: '/admin/activities' }],
  '/admin/registrations': [{ title: '报名管理', path: '/admin/registrations' }],
  '/admin/feedback': [{ title: '反馈管理', path: '/admin/feedback' }],
  '/admin/system/settings': [
    { title: '系统管理', path: '' },
    { title: '系统设置', path: '/admin/system/settings' }
  ],
  '/admin/system/logs': [
    { title: '系统管理', path: '' },
    { title: '操作日志', path: '/admin/system/logs' }
  ],
  '/admin/system/backup': [
    { title: '系统管理', path: '' },
    { title: '数据备份', path: '/admin/system/backup' }
  ],
  '/admin/statistics': [{ title: '数据统计', path: '/admin/statistics' }]
}

const activeMenu = computed(() => {
  return route.path
})

const breadcrumbList = computed(() => {
  const path = route.path
  return breadcrumbMap[path] || [{ title: '未知页面', path }]
})

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
  // 保存到本地存储
  localStorage.setItem('admin-sidebar-collapse', isCollapse.value.toString())
}

const loadUserInfo = async () => {
  try {
    const response = await api.get('/admin/profile')
    const data = response.data.data
    
    Object.assign(userInfo, data)
    
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }
}

const loadNotifications = async () => {
  try {
    const response = await api.get('/admin/notifications', {
      params: { size: 10, unreadOnly: false }
    })
    const data = response.data.data
    
    notifications.value = data.data || []
    unreadNotifications.value = data.unreadCount || 0
    
  } catch (error) {
    console.error('加载通知失败:', error)
  }
}

const markAsRead = async (notificationId) => {
  try {
    await api.put(`/admin/notifications/${notificationId}/read`)
    
    // 更新本地状态
    const notification = notifications.value.find(n => n.id === notificationId)
    if (notification && !notification.read) {
      notification.read = true
      unreadNotifications.value = Math.max(0, unreadNotifications.value - 1)
    }
    
  } catch (error) {
    console.error('标记通知已读失败:', error)
  }
}

const markAllAsRead = async () => {
  try {
    await api.put('/admin/notifications/read-all')
    
    // 更新本地状态
    notifications.value.forEach(notification => {
      notification.read = true
    })
    unreadNotifications.value = 0
    
    ElMessage.success('已标记全部通知为已读')
    
  } catch (error) {
    console.error('标记全部已读失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleNotificationCommand = (command) => {
  if (command === 'viewAll') {
    router.push('/admin/notifications')
  }
}

const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/admin/profile')
      break
      
    case 'settings':
      router.push('/admin/system/settings')
      break
      
    case 'logout':
      try {
        await ElMessageBox.confirm(
          '确定要退出登录吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await userStore.logout()
        router.push('/login')
        
      } catch (error) {
        // 用户取消
      }
      break
  }
}

// 监听路由变化，更新面包屑
watch(
  () => route.path,
  () => {
    // 可以在这里添加页面切换的逻辑
  },
  { immediate: true }
)

onMounted(() => {
  // 从本地存储恢复侧边栏状态
  const savedCollapse = localStorage.getItem('admin-sidebar-collapse')
  if (savedCollapse !== null) {
    isCollapse.value = savedCollapse === 'true'
  }
  
  loadUserInfo()
  loadNotifications()
  
  // 定期刷新通知
  const notificationInterval = setInterval(loadNotifications, 30000) // 30秒刷新一次
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(notificationInterval)
  })
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
}

.sidebar {
  background: #304156;
  transition: width 0.3s ease;
  overflow: hidden;
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #434a50;
  padding: 0 20px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
  color: white;
}

.logo-icon,
.logo-icon-collapsed {
  font-size: 24px;
  color: #409eff;
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
}

.sidebar-menu {
  border: none;
  background: #304156;
}

.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  color: #bfcbd9;
  border-bottom: none;
}

.sidebar-menu :deep(.el-menu-item:hover),
.sidebar-menu :deep(.el-sub-menu__title:hover) {
  background-color: #434a50;
  color: white;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  background-color: #409eff;
  color: white;
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item) {
  background-color: #1f2d3d;
  color: #bfcbd9;
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item:hover) {
  background-color: #434a50;
  color: white;
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item.is-active) {
  background-color: #409eff;
  color: white;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.collapse-btn {
  font-size: 18px;
  color: #606266;
}

.breadcrumb {
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.notification-btn {
  font-size: 18px;
  color: #606266;
  padding: 8px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 600;
  color: #303133;
}

.notification-empty {
  padding: 20px;
  text-align: center;
}

.notification-list {
  max-height: 300px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f5f7fa;
  cursor: pointer;
  transition: background-color 0.3s ease;
  position: relative;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #f0f9ff;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.notification-desc {
  font-size: 12px;
  color: #606266;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-dot {
  width: 6px;
  height: 6px;
  background: #409eff;
  border-radius: 50%;
  margin-left: 8px;
}

.view-all {
  text-align: center;
  color: #409eff;
  border-top: 1px solid #e4e7ed;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.username {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.dropdown-icon {
  font-size: 12px;
  color: #909399;
  transition: transform 0.3s ease;
}

.main-content {
  flex: 1;
  background: #f0f2f5;
  overflow-y: auto;
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-layout {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100% !important;
    height: auto;
  }
  
  .sidebar-header {
    justify-content: space-between;
  }
  
  .header {
    padding: 0 16px;
  }
  
  .header-left {
    gap: 12px;
  }
  
  .header-right {
    gap: 12px;
  }
  
  .username {
    display: none;
  }
  
  .main-content {
    padding: 16px;
  }
}

/* 暗色主题支持 */
@media (prefers-color-scheme: dark) {
  .header {
    background: #1d1e1f;
    border-bottom-color: #414243;
  }
  
  .collapse-btn,
  .notification-btn {
    color: #e5eaf3;
  }
  
  .username {
    color: #e5eaf3;
  }
  
  .main-content {
    background: #0a0a0a;
  }
}
</style>